import { Promise } from 'core-js'
import { getNewCartGoods, reqMergeLocalCart, reqFindCartList, reqInsertCart, reqDeleteCart, reqUpdateCartSku, reqCheckAllCart } from '@/api/cart'

// 购物车状态
export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },

  mutations: {
    // 设置整个列表
    setList (state, list) {
      state.list = list
    },
    // 全选影响小选
    checkEffectAll (state, selected) {
      state.list.forEach(item => { item.selected = selected })
    },
    // 更新
    updateCart (state, goods) {
      const goodsObj = state.list.find(item => item.skuId === goods.skuId)
      // console.log(goodsObj)
      for (const key in goods) {
        if (goods[key] !== null) {
          goodsObj[key] = goods[key]
        }
      }
    },
    // 删除：根据skuId删除对应的商品
    deleteCart (state, skuId) {
      state.list = state.list.filter(item => item.skuId !== skuId)
    },
    // 添加购物车逻辑
    insertCart (state, goods) {
      console.log('添加购物车逻辑')
      // console.log(goods)
      const index = state.list.findIndex(item => item.skuId === goods.skuId)
      // 未添加的商品
      if (index === -1) {
        state.list = [goods, ...state.list]
      } else {
        // 如果添加过，则数量上增加
        state.list[index].count += goods.count
      }
    }
  },

  actions: {
    // 合并本地购物车
    async asyncMergeLocalCart (store) {
      const cartList = store.state.list.map(item => {
        return {
          skuId: item.skuId,
          selected: item.selected,
          count: item.count
        }
      })
      await reqMergeLocalCart(cartList).then(res => {
        console.log('登录成功合并购物车', res)
      })
    },
    //  全选影响小选
    asyncCheckEffectAll (store, selected) {
      return new Promise((resolve, reject) => {
        if (store.rootGetters.token) {
        //  调用接口
          const ids = store.getters.effectiveList.map(item => item.skuId)
          reqCheckAllCart({ selected, ids }).then(res => {
            // 主动更新列表
            store.dispatch('asyncUpdateCart')
            resolve()
          })
        } else {
          store.commit('checkEffectAll', selected)
          resolve()
        }
      })
    },
    // 更新单个列表
    asyncUpdateCartOne (store, goods) {
      return new Promise((resolve, reject) => {
        if (store.rootState.user.profile.token) {
          // console.log('调用接口')
          reqUpdateCartSku(goods)
          resolve()
        } else {
          store.commit('updateCart', goods)
          resolve()
        }
      })
    },
    // 更新商品列表
    asyncUpdateCart (store) {
      return new Promise((resolve, reject) => {
        if (store.rootState.user.profile.token) {
          // console.log('调用接口')
          // 合并成功后，主动从服务器获取购物车列表
          reqFindCartList().then(({ result }) => {
            store.commit('setList', result)
            resolve()
          })
        } else {
          // console.log('直接操作本地数据')
          const arr = []
          store.state.list.forEach(item => {
            arr.push(getNewCartGoods(item.skuId))
          })
          // console.log(arr)
          Promise.all(arr).then((res) => {
            // console.log(1111, res)
            res.forEach((item, index) => {
              store.commit('updateCart', {
                skuId: store.state.list[index].skuId,
                ...item.result
              })
            })
            resolve()
          })
        }
      })
    },
    // 删除
    asyncDeleteCart (store, skuId) {
      return new Promise((resolve, reject) => {
        if (store.rootState.user.profile.token) {
          // console.log('调用接口')
          reqDeleteCart([skuId]).then(res => {
            // 主动更新列表
            store.dispatch('asyncUpdateCart')
            resolve()
          })
        } else {
          // console.log('直接操作本地数据')
          store.commit('deleteCart', skuId)
          resolve()
        }
      })
    },
    // 加入购物车
    asyncInertCart (store, goods) {
      return new Promise((resolve, reject) => {
        if (store.rootState.user.profile.token) {
          // console.log('调用接口')
          reqInsertCart(goods).then(() => {
            // 主动更新列表
            store.dispatch('asyncUpdateCart')
            resolve()
          })
        } else {
          // console.log('直接操作本地数据')
          store.commit('insertCart', goods)
          resolve()
        }
      })
    }
  },
  getters: {
    // 已选择有效商品列表
    selectedList (state, getters) {
      return getters.effectiveList.filter(item => item.selected)
    },
    // 已选择的商品总数
    selectedAllCounts (state, getters) {
      return getters.selectedList.reduce((sum, item) => sum + item.count, 0)
    },
    // 已选择的列表总价
    selectedAllPrice (state, getters) {
      return getters.selectedList.reduce((sum, item) => sum + item.count * item.nowPrice, 0).toFixed(2)
    },
    // 计算全选：是否全部选中
    isAllEffectSelected (state, getters) {
      return getters.effectiveList.every(item => item.selected) && getters.effectiveList.length !== 0
    },
    // 有效商品列表
    effectiveList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品总数量 把effctiveList中的每一项的count叠加起来
    effectiveTotal (state, getters) {
      return getters.effectiveList.reduce((sum, item) =>
        sum + item.count
      , 0)
    },
    effectiveTotalPrice (state, getters) {
      return getters.effectiveList.reduce((sumPrice, item) =>
        sumPrice + item.nowPrice * item.count
      , 0).toFixed(2)
    }
  }
}
